﻿using System.Net.Http;
using System.Text.Json;
using Microsoft.Extensions.Configuration;
using PoemService.Shared;

namespace PoemService.ApiClient
{
    public class PoemServiceApiClient:IPoemService
    {
        private readonly HttpClient _httpClient;

        public PoemServiceApiClient(IHttpClientFactory httpClientFactory, IConfiguration configuration)
        {
            var addr = configuration["PoemServiceApi"];
            _httpClient = httpClientFactory.CreateClient();
            _httpClient.BaseAddress = new Uri(addr);
            _httpClient.Timeout = new TimeSpan(0, 0, 30);
        }
        public async Task<bool> IsPoemLineExist(string line)
        {
            var content=await GetContentFromHttp("IsPoemLineExist?line="+line);
            return content.ToLower() == "true";
        }

        public async Task<PoemLine> GetPoemLine(string line)
        {
            var content = await GetContentFromHttp("GetPoemLine?line=" + line);

            return JsonSerializer.Deserialize<PoemLine>(content);
        }

        public async Task<List<PoemLine>> GetPoemLineByPoemId(string poemId)
        {
            var content = await GetContentFromHttp("GetPoemLineByPoemId?poemId=" + poemId); 
            return JsonSerializer.Deserialize<List<PoemLine>>(content);
        }

        public async Task<Poet> GetPoetByName(string name)
        {
            var content = await GetContentFromHttp("GetPoetByName?name=" + name);
            return JsonSerializer.Deserialize<Poet>(content);
        }

        private async Task<string> GetContentFromHttp(string action)
        {
            var response = await _httpClient.GetAsync(action);
            response.EnsureSuccessStatusCode();
            var content = await response.Content.ReadAsStringAsync();
            return content;
        }
    }
}